import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_my_test/src/ui/base_bloc_state.dart';

//flutter_bloc库page
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('登录页面')),
      body: _buildContent(),
    );
  }

  Widget _buildContent() {

    // return BlocProvider(create: );

    return Center(
      child: TextButton(
        onPressed: () async {
          context
              .read<LoginBloc>()
              .add(PhonePasswordLoginEvent(phone: "123", password: "123"));
        },
        child: const Text("登录"),
      ),
    );
    // return BlocProvider.value(
    //   value: context.read<LoginBloc>(),
    //   child: BlocConsumer<LoginBloc, AppState>(builder: (context, state) {
    //     return Center(
    //       child: TextButton(
    //         onPressed: () async {
    //           context
    //               .read<LoginBloc>()
    //               .add(PhonePasswordLoginEvent(phone: "123", password: "123"));
    //         },
    //         child: const Text("登录"),
    //       ),
    //     );
    //   }, listener: (context, state) {
    //     if (state is AppBusyState) {
    //       const Center(
    //         child: CircularProgressIndicator(),
    //       );
    //     } else if (state is AppSuccessState) {
    //       Navigator.pop(context);
    //     } else if (state is AppErrorState) {
    //       const Center(
    //         child: Text('登录失败'),
    //       );
    //     }
    //   }),
    // );
  }
// widget-> sink-> business logic -> stream -> stream-> widget
}

class LoginBloc extends Bloc<LoginEvent, AppState> {
  LoginBloc(super.initialState) {
    on<PhonePasswordLoginEvent>((event, emit) async {
      emit(AppBusyState());
      String token = await UserService.login(event.phone, event.password);
      emit(AppSuccessState());
    });
  }
}

class UserService {
  static Future<String> login(String mobile, String passWord) async {
    Future.delayed(const Duration(seconds: 2));
    return Future.value("登录成功");
  }
}

abstract class LoginEvent {}

class PhonePasswordLoginEvent extends LoginEvent {
  final String phone;
  final String password;

  PhonePasswordLoginEvent({required this.phone, required this.password});
}
